<?php

namespace App\Admin\Actions\Stock;

use App\Model\Good;
use App\Model\Note;
use App\Model\Stock;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class In extends RowAction
{
    public $name = '入库';

    public function form()
    {
        // 文本输入框
        $this->text('stock-' . $this->getRow()->id, '入库数量')
            ->rules('required|integer|min:0', [
                'required' => "请输入入库数量",
                'integer' => '入库数量为大于0正整数',
                'min' => '入库数量为大于0正整数',
            ]);
    }

    public function handle(Model $model, Request $request)
    {
        $stockModel = new Stock();
        $stockModel->fill([
            'goods_id' => $this->getRow()->id,
            'value' => $request->get('stock-' . $this->getRow()->id),
            'user_user_id' => Admin::user()->id,
            'type' => 1
        ]);
        DB::beginTransaction();
        try {
            Good::query()->where('id', $this->getRow()->id)
                ->increment('stock', $request->get('stock-' . $this->getRow()->id));
            $stockModel->save();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->response()->error('操作失败')->refresh();
        }
        DB::commit();
        return $this->response()->success('操作成功')->refresh();

    }

}
